﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Diagnostics;
using System.Timers;
using System.Windows.Threading;
using Microsoft.Lync.Model;
using System.Runtime.InteropServices;

namespace MediaLync
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private Timer _registryChecker;
		private LyncClient _lyncClient;
		private string _lastNote;

		public MainWindow()
		{
			InitializeComponent();

			Process.Start("ZuneNowPlaying.exe");

			_lyncClient = LyncClient.GetClient();

			_registryChecker = new Timer();
			_registryChecker.Interval = 15 * 1000; // Every 15 seconds
			_registryChecker.AutoReset = true;
			_registryChecker.Elapsed += registryChecker_CheckRegistry;
			_registryChecker.Start();
		}

		void registryChecker_CheckRegistry(object sender, ElapsedEventArgs e)
		{
			RefreshSong();
		}

		public void RefreshSong()
		{
			RegistryKey regkey;
			String title, artist;
			int status;
			try
			{
				regkey = Registry.CurrentUser.OpenSubKey(@"Software\ZuneNowPlaying");
				status = (int)regkey.GetValue("Playing");
				// Do nothing if no track is being played
				if (status == 0)
				{
					regkey.Close();
					return;
				}
				title = regkey.GetValue("Title") as string;
				artist = regkey.GetValue("Artist") as string;

				this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
					delegate()
					{
						TrackArtist = artist;
						TrackTitle = title;
						LyncNote = artist + " - " + title;
					}));
			}
			catch (Exception e)
			{
				// Todo Log Error
			}
		}

		#region Lync Update Code

		public void UpdateLyncNote(string note)
		{
			//Each element of this array must contain a valid enumeration. If null array elements 
			//are passed, an ArgumentException is raised.
			Dictionary<PublishableContactInformationType, object> publishData = new Dictionary<PublishableContactInformationType, object>();
			publishData.Add(PublishableContactInformationType.PersonalNote, note);
			publishData.Add(PublishableContactInformationType.Availability, ContactAvailability.Free);

			SendPublishRequest(publishData, "Personal Note and Availability");
		}

		private void SendPublishRequest(
		   Dictionary<PublishableContactInformationType, object> publishData,
			string PublishId)
		{
			object publishState = (object)PublishId;
			object[] _PublishAsyncState = { _lyncClient.Self, publishState };
			try
			{
				_lyncClient.Self.BeginPublishContactInformation(
					publishData,
					PublicationCallback,
					_PublishAsyncState);
			}
			catch (COMException ce)
			{
				MessageBox.Show("publish COM exception: " + ce.ErrorCode.ToString());
			}
			catch (ArgumentException ae)
			{
				MessageBox.Show("publish Argument exception: " + ae.Message);
			}
		}

		private void PublicationCallback(IAsyncResult ar)
		{
			if (ar.IsCompleted)
			{
				object[] _asyncState = (object[])ar.AsyncState;
				((Self)_asyncState[0]).EndPublishContactInformation(ar);
			}
		}

		#endregion

		#region Data Setters

		protected string TrackArtist
		{
			set
			{
				if (lblArtist.Content.ToString().Trim() != value.Trim())
				{
					lblArtist.Content = value;
				}
			}
		}

		protected string TrackTitle
		{
			set
			{
				if (lblTitle.Content.ToString().Trim() != value.Trim())
				{
					lblTitle.Content = value;
				}
			}
		}

		protected string LyncNote
		{
			set
			{
				if (!value.Equals(_lastNote))
				{
					_lastNote = value;
					UpdateLyncNote(value);
				}
			}
		}

		#endregion

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			_registryChecker.Stop();
			LyncNote = "";
		}

		
	}
}
